import { NextRequest, NextResponse } from 'next/server';
import { verifyToken } from '@/utils/auth';
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';
import { UserModel } from '@/models/user';

export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const token = request.headers.get('Authorization')?.replace('Bearer ', '');
    if (!token) {
      return NextResponse.json({ error: '未提供认证token' }, { status: 401 });
    }

    const decoded = verifyToken(token);
    if (!decoded) {
      return NextResponse.json({ error: '无效的token' }, { status: 401 });
    }

    const userId = decoded.userId;

    // 获取上传的文件
    const formData = await request.formData();
    const file = formData.get('avatar') as File;

    if (!file) {
      return NextResponse.json({ error: '未选择文件' }, { status: 400 });
    }

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      return NextResponse.json({ error: '只支持图片文件' }, { status: 400 });
    }

    // 验证文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
      return NextResponse.json({ error: '文件大小不能超过5MB' }, { status: 400 });
    }

    // 获取文件扩展名
    const fileExtension = path.extname(file.name);
    
    // 生成唯一文件名
    const filename = `avatar_${userId}_${Date.now()}${fileExtension}`;
    
    // 确保上传目录存在
    const uploadDir = path.join(process.cwd(), 'public', 'uploads', 'avatars');
    await mkdir(uploadDir, { recursive: true });
    
    // 完整的文件路径
    const filepath = path.join(uploadDir, filename);
    
    // 将文件写入磁盘
    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);
    await writeFile(filepath, buffer);
    
    // 生成可访问的URL
    const avatarUrl = `/uploads/avatars/${filename}`;
    
    // 更新数据库中的用户头像URL
    try {
      await UserModel.query(
        'UPDATE users SET avatar = ? WHERE id = ?',
        [avatarUrl, userId]
      );
      
      console.log(`用户 ${userId} 的头像已更新为: ${avatarUrl}`);
    } catch (dbError) {
      console.error('更新数据库头像URL失败:', dbError);
      return NextResponse.json({ 
        error: '头像上传成功但更新数据库失败，请重试' 
      }, { status: 500 });
    }

    return NextResponse.json({ 
      message: '头像上传成功',
      avatarUrl 
    }, { status: 200 });

  } catch (error) {
    console.error('头像上传失败:', error);
    return NextResponse.json({ 
      error: '头像上传失败，请重试' 
    }, { status: 500 });
  }
} 